import { ref } from 'vue'

// 会员等级配置
export const VIP_LEVELS = {
  FREE: {
    name: '免费用户',
    dailyLimit: 5, // 每日免费次数
    voiceTypes: ['yunyang_general'], // 可用音色
    maxDuration: 60, // 最大时长(秒)
    hasAds: true
  },
  VIP1: {
    name: 'VIP会员',
    dailyLimit: 100,
    voiceTypes: ['yunyang_general', 'yunyang_friendly', 'yunyang_reading'],
    maxDuration: 300,
    hasAds: false,
    price: 15 // 月费
  },
  VIP2: {
    name: '超级会员',
    dailyLimit: -1, // 无限制
    voiceTypes: ['yunyang_general', 'yunyang_friendly', 'yunyang_reading', 'yunyang_emotional', 'yunyang_anchor'],
    maxDuration: 3600,
    hasAds: false,
    price: 30
  },
  ENTERPRISE: {
    name: '企业版',
    dailyLimit: -1,
    voiceTypes: 'all',
    maxDuration: -1,
    hasAds: false,
    hasAPI: true,
    price: 299
  }
}

// 用户状态
export const userState = ref({
  id: '0W1FFE',
  nickname: '0W1FFE',
  avatar: '/static/images/default-avatar.png',
  vipLevel: 'FREE',
  vipExpireDate: null,
  coins: 4,
  usedCount: 0, // 今日已使用次数
  inviteCode: '',
  inviteCount: 0,
  watchedVideos: 0,
  maxVideosPerDay: 5,
  totalConvertCount: 0, // 总转换次数
  convertHistory: [], // 转换历史
  apiKey: '', // API密钥
  apiUsage: 0 // API调用次数
})

// 签到状态
export const signInState = ref({
  currentDay: 0,
  rewards: [2, 5, 8, 8, 10, 10, 15],
  hasSignedToday: false
})

// 广告配置
export const AD_CONFIG = {
  REWARD_VIDEO: {
    adUnitId: 'adunit-xxx', // 激励视频广告ID
    reward: 2, // 观看奖励金币数
    maxDaily: 5 // 每日最大观看次数
  },
  INTERSTITIAL: {
    adUnitId: 'adunit-xxx', // 插屏广告ID
    interval: 5 // 每5次使用显示一次
  },
  BANNER: {
    adUnitId: 'adunit-xxx' // Banner广告ID
  }
}

// 签到
export async function signIn() {
  try {
    if (signInState.value.hasSignedToday) {
      throw new Error('今日已签到')
    }
    
    const reward = signInState.value.rewards[signInState.value.currentDay]
    userState.value.coins += reward
    signInState.value.hasSignedToday = true
    signInState.value.currentDay = (signInState.value.currentDay + 1) % 7
    
    return reward
  } catch (error) {
    console.error('签到失败:', error)
    throw error
  }
}

// 观看广告奖励
export async function watchVideoReward() {
  try {
    if (userState.value.watchedVideos >= userState.value.maxVideosPerDay) {
      throw new Error('今日观看次数已达上限')
    }
    
    userState.value.coins += AD_CONFIG.REWARD_VIDEO.reward
    userState.value.watchedVideos++
    
    return {
      reward: AD_CONFIG.REWARD_VIDEO.reward,
      remainingCount: userState.value.maxVideosPerDay - userState.value.watchedVideos
    }
  } catch (error) {
    console.error('观看视频失败:', error)
    throw error
  }
}

// 检查使用权限
export function checkUsagePermission(duration) {
  const vipConfig = VIP_LEVELS[userState.value.vipLevel]
  
  // 检查每日使用次数
  if (vipConfig.dailyLimit !== -1 && userState.value.usedCount >= vipConfig.dailyLimit) {
    throw new Error('今日使用次数已达上限')
  }
  
  // 检查时长限制
  if (vipConfig.maxDuration !== -1 && duration > vipConfig.maxDuration) {
    throw new Error(`免费用户最大时长限制为${vipConfig.maxDuration}秒`)
  }
  
  // 检查金币余额
  if (userState.value.vipLevel === 'FREE' && userState.value.coins < 1) {
    throw new Error('金币不足，请观看广告获取金币')
  }
  
  return true
}

// 使用次数记录
export function recordUsage(duration) {
  userState.value.usedCount++
  userState.value.totalConvertCount++
  
  // 免费用户扣除金币
  if (userState.value.vipLevel === 'FREE') {
    userState.value.coins--
  }
  
  // 记录历史
  userState.value.convertHistory.unshift({
    time: new Date().toISOString(),
    duration,
    type: 'convert'
  })
}

// 开通会员
export async function activateVip(level, months = 1) {
  try {
    if (!VIP_LEVELS[level]) {
      throw new Error('无效的会员等级')
    }
    
    // TODO: 处理支付逻辑
    
    const expireDate = new Date()
    expireDate.setMonth(expireDate.getMonth() + months)
    
    userState.value.vipLevel = level
    userState.value.vipExpireDate = expireDate.toISOString()
    
    return true
  } catch (error) {
    console.error('开通会员失败:', error)
    throw error
  }
}

// 生成API密钥
export async function generateApiKey() {
  try {
    if (userState.value.vipLevel !== 'ENTERPRISE') {
      throw new Error('仅企业版可使用API')
    }
    
    // TODO: 生成API密钥
    userState.value.apiKey = 'api_' + Math.random().toString(36).substr(2)
    
    return userState.value.apiKey
  } catch (error) {
    console.error('生成API密钥失败:', error)
    throw error
  }
}

// 邀请好友
export async function inviteFriend(friendId) {
  try {
    userState.value.coins += 5
    userState.value.inviteCount++
    
    return {
      reward: 5,
      inviteCount: userState.value.inviteCount
    }
  } catch (error) {
    console.error('邀请失败:', error)
    throw error
  }
}

// 绑定上级
export async function bindInviter(inviterCode) {
  try {
    // TODO: 实现绑定上级逻辑
    return true
  } catch (error) {
    console.error('绑定上级失败:', error)
    throw error
  }
}

// 使用金币
export async function useCoins(amount) {
  try {
    if (userState.value.coins < amount) {
      throw new Error('金币不足')
    }
    
    userState.value.coins -= amount
    return true
  } catch (error) {
    console.error('使用金币失败:', error)
    throw error
  }
} 